package cn.sq.scaffold.ffmpeg.video.controller;


import cn.sq.scaffold.ffmpeg.config.NonStaticResourceHttpRequestHandler;
import cn.sq.scaffold.ffmpeg.config.ResponseBean;
import cn.sq.scaffold.ffmpeg.config.StatusCode;
import cn.sq.scaffold.ffmpeg.config.base.BaseController;
import cn.sq.scaffold.ffmpeg.config.base.BaseSelectSymbol;
import cn.sq.scaffold.ffmpeg.config.entity.SymbolPlus;
import cn.sq.scaffold.ffmpeg.constants.FfmpegConstants;
import cn.sq.scaffold.ffmpeg.exception.BaseExeception;
import cn.sq.scaffold.ffmpeg.exception.FileChangeExeception;
import cn.sq.scaffold.ffmpeg.hander.FfmpegHander;
import cn.sq.scaffold.ffmpeg.utils.CmdUtils;
import cn.sq.scaffold.ffmpeg.video.entity.SqVideo;
import cn.sq.scaffold.ffmpeg.video.service.ISqVideoService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author SQ
 * @since 2020-11-24
 */
@RestController
@RequestMapping("/video")
@AllArgsConstructor
public class SqVideoController extends BaseController<SqVideo, ISqVideoService> {
    @Autowired
    private FfmpegHander ffmpegHander;
    @Autowired
    NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @RequestMapping("/list_by_page")
//    @ApiOperation(value = "根据条件查询问题")
//    @ApiOperationSupport(params = @DynamicParameters(name = "页面对象(IPage扩展对象)", properties = {
//            @DynamicParameter(name = "pagesize", value = "每页长度", example = "10", required = true, dataTypeClass = String.class),
//            @DynamicParameter(name = "pageindex", value = "第几页", example = "1", required = true, dataTypeClass = String.class),
//            @DynamicParameter(name = "ascs", value = "正序字段", required = true, dataTypeClass = String.class),
//            @DynamicParameter(name = "desc", value = "倒叙字段", required = true, dataTypeClass = String.class),
//    }))
    public ResponseBean list_by_page(@RequestBody HashMap<String, String> map) {
        SymbolPlus symbolPlus = BaseSelectSymbol.select_Analysis(map);
        IPage<SqVideo> sqVideoIPage = super.base_get_list_by_page(symbolPlus);
        return new ResponseBean(0, "获取数据成功", sqVideoIPage);
    }

    /**
     * @param sqVideo
     * @return 添加结果
     */
//    @ApiOperation(value = "添加")
    @RequestMapping("save")
    public ResponseBean save(@RequestBody SqVideo sqVideo) {
        boolean add = super.add(sqVideo);
        return StatusCode.successResponseBean(add);
    }


    //    @ApiOperation(value = "删除")
    @RequestMapping("del")
    public ResponseBean delete(@RequestBody HashMap<String, String> map) {
        SqVideo id = super.sService.getById(map.get("id"));
        String videoPlayUrl = id.getVideoPlayUrl();
        String imageUrl = id.getImageUrl();
        boolean delete = new File(FfmpegConstants.OUTPUTFILEPATH + videoPlayUrl).delete();
        boolean delete1 = new File(FfmpegConstants.OUTPUTFILEPATH + imageUrl).delete();
        boolean del = super.del(map.get("id"));
        return StatusCode.successResponseBean(del);
    }

    //    @ApiOperation(value = "修改")
    @RequestMapping("modify")
    public ResponseBean modify(@RequestBody Map<String, String> map) {
        UpdateWrapper updateWrapper = BaseSelectSymbol.update_Analysis(map);
        boolean update = super.update(updateWrapper);
        return StatusCode.successResponseBean(update);
    }

    /**
     * @param file        文件
     * @param imagefile   图片文件
     * @param initiator   发起人
     * @param mainContent 主要内容
     * @param author      文章作者
     * @param title       文章标题
     * @param unit        作者单位
     * @param introduce   简介
     * @return
     */

    @RequestMapping("asyncprocessvideo")
    public ResponseBean asyncprocessvideo(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "imagefile") MultipartFile imagefile, String initiator, String mainContent, String author, String title, String unit, String introduce) throws IOException, ServletException, BaseExeception {
        InputStream inputStream = file.getInputStream();

        Thread thread = new Thread(() -> {

            try {
                String originalFilename = UUID.randomUUID() + CmdUtils.getFileSuffix(imagefile.getOriginalFilename());
                String oldFilepath = FfmpegConstants.IMAGEPATH + originalFilename;
//                boolean b = CmdUtils.multipartFileToFile(imagefile, oldFilepath);
                int copy = IOUtils.copy(imagefile.getInputStream(), new FileOutputStream(oldFilepath));
                String syncprocess = null;
                syncprocess = ffmpegHander.syncprocess(inputStream,file.getOriginalFilename());

                SqVideo sqVideo = new SqVideo().setAuthor(author)
                        .setFlag(1)
                        .setInitiator(initiator)
                        .setInitTime(LocalDateTime.now())
                        .setTitle(title)
                        .setMainContent(mainContent)
                        .setIntroduce(introduce)
                        .setUnit(unit)
                        .setModifyTime(LocalDateTime.now())
                        .setImageUrl(originalFilename)
                        .setVideoPlayUrl(syncprocess);
                super.add(sqVideo);
            } catch (BaseExeception | FileChangeExeception | IOException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        return StatusCode.R_SUCCESS;
    }

    @RequestMapping("playervideo")
    public void playervideo(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, BaseExeception {
        String filePath = FfmpegConstants.OUTPUTFILEPATH + filename;
        if (Files.exists(Paths.get(filePath))) {
            String mimeType = Files.probeContentType(Paths.get(filePath));

            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, Paths.get(filePath));
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);

        } else {
            throw new BaseExeception("视频流转化异常", StatusCode.Error);

        }
//        throw new BaseExeception("视频流转化异常", StatusCode.Error);

    }
}
